import 'package:OASys/api/EventApi.dart';
import 'package:OASys/components/FormComponents.dart';
import 'package:OASys/entity/EventVo.dart';
import 'package:OASys/utils/strUtils.dart';
import 'package:OASys/views/icon/myIcons.dart';
import 'package:flutter/material.dart';

class EventCheck extends StatefulWidget {
  final int status;
  EventCheck(this.status, {Key key});

  @override
  _EventCheckState createState() => _EventCheckState();
}

class _EventCheckState extends State<EventCheck>
    with SingleTickerProviderStateMixin {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  double _addPadding = 30;
  bool flag = false;
  IconData actionIcon = MyIcons.spread;
  String loadText = "加载更多";

  List<EventVo> eventVoList = [];
  int page = 1;
  int limit = 10;
  int total = 0;
  AnimationController _controller;
  @override
  void initState() {
    super.initState();
    print(widget.status);
    _getList();
    _controller =
        AnimationController(vsync: this, duration: Duration(milliseconds: 500))
          ..addListener(() {
            setState(() {
              _addPadding = 30 + 100 * _controller.value;
            });
          });
  }

  //获取需审核列表
  void getCheckList() {
    EventApi().checkList(
      page,
      limit,
      success: (res) {
        if (res == null || res.length == 0) {
          print('无数据');
          setState(() {
            loadText = "没有更多了";
          });
          return;
        }
        setState(() {
          eventVoList.addAll(res);
          total += res.length;
          page++;
          loadText = "加载更多";
        });
        res.forEach((element) {
          print(element.toJson().toString());
        });
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  //获取已审核列表
  void getCheckedList() {
    EventApi().checkedList(
      page,
      limit,
      success: (res) {
        if (res == null || res.length == 0) {
          print('无数据');
          setState(() {
            loadText = "没有更多了";
          });
          return;
        }
        setState(() {
          eventVoList.addAll(res);
          total += res.length;
          print(total);
          page++;
          loadText = "加载更多";
        });
        res.forEach((element) {
          print(element.toJson().toString());
        });
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  //跳转编辑
  Future<void> toEdit(EventVo item, bool isEdit) async {
    Navigator.of(context, rootNavigator: true).pop();
    var result = await Navigator.of(context).pushNamed(
      '/eventEdit',
      arguments: {'info': item.toJson(), 'isEdit': isEdit},
    );
    if (result == null || !result) {
      print('未编辑成功');
    } else {
      updateData();
      print('编辑成功');
    }
  }

  // 更新数据
  void updateData() {
    setState(() {
      resetQueryData();
      _getList();
    });
  }

  void _getList() {
    if (widget.status == 0) {
      getCheckList();
    } else {
      getCheckedList();
    }
  }

  void resetQueryData() {
    setState(() {
      eventVoList = [];
      loadText = "加载更多";
      page = 1;
      limit = 10;
      total = 0;
    });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  // 加载更多
  void doLoad() {
    print(page);
    if (widget.status == 0) {
      getCheckList();
    } else {
      getCheckedList();
    }
  }

  void doSave(EventVo item) {
    var form = formKey.currentState;
    if (form.validate()) {
      form.save();
      setState(() {
        EventApi().save(item, success: (res) {
          Navigator.of(context, rootNavigator: true).pop();
          Navigator.of(context, rootNavigator: true).pop();
          showSuccessMessage(context);
          updateData();
        }, error: (err) {
          print(err.code);
          showFailMessage(context);
        });
      });
    }
  }

  // 审核操作
  checkEvent(EventVo item, int status) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            titlePadding: EdgeInsets.all(0),
            title: Container(
              height: 50,
              alignment: Alignment.center,
              child: Text(
                '审核批复',
                style: TextStyle(color: Colors.white),
              ),
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(3),
                  topRight: Radius.circular(3),
                ),
              ),
            ),
            contentPadding: EdgeInsets.all(0),
            content: Container(
              height: 300,
              width: 300,
              decoration: BoxDecoration(
                color: Color.fromRGBO(250, 250, 250, 1),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Container(
                margin: EdgeInsets.only(
                  top: 20,
                  bottom: 20,
                ),
                height: 260,
                width: 300,
                child: Form(
                  key: formKey,
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          PrefixContanier("审核批复:"),
                          FormText(
                            hintText: "请输入审核批复内容",
                            validator: (content) {
                              if (content.length > 50) {
                                return "审核批复过长";
                              } else if (content.length <= 0) {
                                return "审核批复过短";
                              }
                            },
                            onSave: (value) {
                              item.checkContent = value;
                            },
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
            actions: <Widget>[
              RaisedButton(
                color: Color.fromRGBO(33, 150, 243, 1),
                child: Text('保 存'),
                onPressed: () {
                  item.status = status;
                  doSave(item);
                },
              ),
              RaisedButton(
                color: Color.fromRGBO(245, 108, 108, 1),
                child: Text('取 消'),
                onPressed: () {
                  Navigator.of(context, rootNavigator: true).pop();
                },
              ),
            ],
          );
        });
  }

  // 显示卡片
  onClick(EventVo item) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          titlePadding: EdgeInsets.all(0),
          title: Container(
            height: 50,
            alignment: Alignment.center,
            child: Text(
              '用户信息',
              style: TextStyle(color: Colors.white),
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(3),
                topRight: Radius.circular(3),
              ),
            ),
          ),
          contentPadding: EdgeInsets.all(0),
          content: Container(
            height: 300,
            width: 300,
            decoration: BoxDecoration(
              color: Color.fromRGBO(250, 250, 250, 1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Container(
              margin: EdgeInsets.only(
                top: 20,
                bottom: 20,
              ),
              height: 260,
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Column(
                  children: [
                    InfoItem('流程名称',
                        StrUtils.isNotBlank(item.name) ? item.name : "无"),
                    InfoItem('流程状态', item.statusName),
                    InfoItem('发起人', item.userName),
                    InfoItem('审核人', item.checkerName),
                    InfoItem('审核内容', item.content),
                    InfoItem(
                        '审核时间',
                        StrUtils.isNotBlank(item.checkTime)
                            ? item.checkTime
                            : "暂未审核"),
                    InfoItem('发起时间', item.createTime),
                  ],
                ),
              ),
            ),
          ),
          actions: <Widget>[
            Visibility(
              visible: widget.status == 0,
              child: RaisedButton(
                color: Color.fromRGBO(33, 150, 243, 1),
                child: Text(
                  '通 过',
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () {
                  checkEvent(item, 1);
                },
              ),
            ),
            Visibility(
              visible: widget.status == 0,
              child: RaisedButton(
                color: Colors.redAccent,
                child: Text('驳 回'),
                onPressed: () {
                  checkEvent(item, 1);
                },
              ),
            ),
            RaisedButton(
              color: Color.fromRGBO(103, 194, 58, 1),
              child: Text(
                '查 看',
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () {
                toEdit(item, false);
              },
            ),
          ],
        );
      },
    );
  }

  /// 按钮收缩展开
  shrinkage() {
    setState(() {
      flag = !flag;
      if (flag) {
        actionIcon = MyIcons.shrink;
        _controller.forward();
      } else {
        actionIcon = MyIcons.spread;
        _controller.reverse();
      }
    });
  }

  Widget buildLoadMore() {
    return FlatButton(
      child: Container(
        child: Text(
          loadText,
          style: TextStyle(color: Colors.blue, fontSize: 12),
        ),
      ),
      onPressed: () {
        doLoad();
      },
    );
  }

  /// 构建卡片
  Widget buildListItem(int index) {
    return FlatButton(
      child: Card(
        child: Container(
          width: 800,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ItemTitle(eventVoList[index].name),
              ItemContext(
                  '状态：',
                  StrUtils.isNotBlank(eventVoList[index].statusName)
                      ? eventVoList[index].statusName
                      : '无'),
              ItemContext(
                  '发起人：',
                  StrUtils.isNotBlank(eventVoList[index].userName)
                      ? eventVoList[index].userName
                      : '无'),
              ItemContext(
                  '开始时间：',
                  StrUtils.isNotBlank(eventVoList[index].beginTime)
                      ? eventVoList[index].beginTime
                      : '无'),
              ItemContext('结束时间：', eventVoList[index].overTime),
            ],
          ),
        ),
      ),
      onPressed: () {
        onClick(eventVoList[index]);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          padding: EdgeInsets.only(top: 10, bottom: 10),
          height: 720,
          child: ListView.builder(
            itemCount: total + 1,
            itemBuilder: (BuildContext context, int index) {
              if (index == total) {
                return buildLoadMore();
              }
              return buildListItem(index);
            },
          ),
        ),
        Positioned(
          right: _addPadding,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.yellow,
              child: Icon(
                MyIcons.query,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: () {
                print('查询');
              },
            ),
          ),
        ),
        Positioned(
          right: 30,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.blue,
              child: Icon(
                actionIcon,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: shrinkage,
            ),
          ),
        ),
      ],
    );
  }
}
